package com.lanou3g.ptp.organize.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanou3g.ptp.entity.School;
import com.lanou3g.ptp.organize.mapper.SchoolMapper;
import com.lanou3g.ptp.organize.service.SchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class SchoolServiceImpl implements SchoolService {
    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${REDIS_SCHOOL_KEY_PREFIX}")
    private String REDIS_SCHOOL_KEY_PREFIX;

    @Value("${REDIS_SCHOOL_KEY_EXPIRE}")
    private Long REDIS_SCHOOL_KEY_EXPIRE;

    @Override
    public void addSchool(School school) {
        Date date = new Date();
        school.setCreateTime(date);
        school.setUpdateTime(date);
        school.setStatus(0);
        schoolMapper.addSchool(school);
    }

    @Override
    public School findByName(String name) {
        School school=schoolMapper.findByName(name);
        return school;
    }

    @Override
    public School findById(Long id) {
        String redisKey = REDIS_SCHOOL_KEY_PREFIX + id;
        String sc = redisTemplate.opsForValue().get(redisKey);
        if (sc == null){
            School school = schoolMapper.findById(id);
            String s = JSON.toJSONString(school);
            redisTemplate.opsForValue().set(redisKey,s,REDIS_SCHOOL_KEY_EXPIRE,TimeUnit.MINUTES);
            return school;
        }else {
            School school = JSON.parseObject(sc, School.class);
            redisTemplate.expire(redisKey,REDIS_SCHOOL_KEY_EXPIRE,TimeUnit.MINUTES);
            return school;
        }
    }

    @Override
    public List<School> findByIds(Long[] ids) {
        List<School> schools = schoolMapper.findByIds(ids);
        return schools;
    }

    @Override
    public List<School> findAll(Integer page, Integer size)
 {
     Page<School> pages = PageHelper.startPage(page, size);

     List<School> schools = schoolMapper.findAll();
        return pages;
    }

    @Override
    public void updateById(Long id, School school) {
        school.setUpdateTime(new Date());
        schoolMapper.updateById(id, school);
    }

    @Override
    public void deleteById(Long id) {
        schoolMapper.deleteById(id);
    }

    @Override
    public void deleteByIds(Long[] ids) {
        schoolMapper.deleteByIds(ids);
    }
}
